package com.controller;


import com.entity.User;
import com.google.gson.Gson;
import com.service.impl.BlogServiceImpl;
import com.service.impl.UserServiceImpl;
import com.service.intf.BlogService;
import com.service.intf.UserService;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();
    BlogService blogService=new BlogServiceImpl();

    /**
     * 处理登录的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //role是admin和user都可以，因为底层是只要你用户名和密码对了就行
        User loginUser = userService.login(new User(null, username, password, "user", 0));
        List<User> adminUsers = userService.queryUserByRoleAdmin();
        if (loginUser == null) {
            //把错误信息，和回显的表单项信息，保存到Request域中
            req.setAttribute("msg", "用户名或密码错误！");
            req.setAttribute("username", username);

            //跳回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);

        } else {

            User user = userService.queryUserByUsername(username);
            System.out.println(user);
            if (user.getIsFreezed() == 1) {   //说明该用户被冻结
                //把错误信息，和回显的表单项信息，保存到Request域中
                req.setAttribute("msg", "您的用户已经被冻结，请联系管理员！");
                req.setAttribute("username", username);

                //跳回登录页面
                req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);

            } else {//说明该用户没有被冻结
                req.getSession().setAttribute("user", user);
                req.getSession().setAttribute("adminUsers", adminUsers);
                req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);

            }

        }
    }

    /**
     * 处理注册的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // String email = req.getParameter("email");
        //   String code = req.getParameter("code");


        if (userService.existsUsername(username)) {
            //用户名已存在，说明不可用
            System.out.println("用户名[" + username + "]已存在");

            //把错误信息，和回显的表单项信息，保存到Request域中
            req.setAttribute("msg", "用户名已存在！");
            req.setAttribute("username", username);
//            req.setAttribute("email",email);
            //调转到注册失败页面
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);

        } else {
            //用户名不存在，说明可用，调用service保存在数据库
            userService.registerUser(new User(null, username, password,  "user", 0));
            //调转到注册成功页面
            req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
        }
    }

//    /**
//     * 查询用户的关注的人以及粉丝
//     * @param req
//     * @param resp
//     * @throws ServletException
//     * @throws IOException
//     */
//    protected void  queryFollow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//       // String  username = (String) req.getAttribute("username");
//        String username = req.getParameter("username");
//        Integer followerNum = userService.queryFollowerNum(username);
//        System.out.println(followerNum);
//        System.out.println("-----------");
//        req.setAttribute("followerNum", followerNum);
//
//        List<Relation> followerName = userService.queryFollowerName(username);
//        List<Relation> followedName = userService.queryFollowedName(username);
//        System.out.println(followedName);
//        System.out.println("----------");
//        System.out.println(followerName);
//        System.out.println("------------");
//        req.getSession().setAttribute("followerName", followerName);
//       req.getSession().setAttribute("followedName", followedName);
//
//      req.getRequestDispatcher("/pages/follow/follower.jsp").forward(req, resp);
//
//    }

    /**
     * 注销
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getSession().invalidate();
        //重定向到首页
        resp.sendRedirect(req.getContextPath());
    }

    /**
     * 1、查询注册的用户名是否存在
     * 2、查询修改个人信息时用户名是否存在（如果修改的名字和原来相同，这里认为用户名依然是可用的）
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的参数username
        String username = req.getParameter("username");

        //如果是修改用户个人信息，则获取用户原本的名字
        User user = (User) req.getSession().getAttribute("user");
        String originalUserName = user.getUsername();

        // 调用 userService.existsUsername();
        boolean existsUsername = userService.existsUsername(username);

        //如果用户本人修改的用户名和原本的一样，这里认为用户名是可用的（因为有可能用户只是想修改密码）
        if(username.equals(originalUserName)){
            existsUsername=false;
        }
        // 把返回的结果封装成为 map 对象
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername", existsUsername);
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }

    /**
     * 判断当前用户是不是管理员
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void isAdmin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的参数username
        String userName = req.getParameter("userName");
        // 调用 userService.existsUsername();
        List<User> admins = userService.queryUserByRoleAdmin();

        // 把返回的结果封装成为 map 对象
        Map<String, Object> resultMap = new HashMap<>();
        boolean admin=false;

        for (User ad : admins) {
            //说明当前用户是管理员
            if(ad.getUsername().equals(userName)){
               admin=true;
            }
        }
        resultMap.put("admin", admin);
        System.out.println("admin"+admin);
        req.getSession().setAttribute("admin",admin);

        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }

    /**
     * 查询当前用户是否被冻结
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void isFreezed(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取请求的参数currentUserName，即为当前管理员查看到的用户
        String currentUserName = req.getParameter("currentUserName");
        List<User> isFreezedUsers = userService.queryIsFreezedUser();

        // 把返回的结果封装成为 map 对象
        Map<String, Object> resultMap = new HashMap<>();
        boolean isFreezed=false;

        for (User isFreezedUser : isFreezedUsers) {
            if(currentUserName.equals(isFreezedUser.getUsername())){  //说明当前用户是被冻结的状态
                isFreezed=true;

            }
        }

        resultMap.put("isFreezed", isFreezed);

        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }


    /**
     * 管理员查询所有被冻结用户
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void queryIsFreezedUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<User> isFreezedUser = userService.queryIsFreezedUser();
        req.getSession().setAttribute("isFreezedUser",isFreezedUser);

        req.getRequestDispatcher("/pages/user/isFreezedUser.jsp").forward(req, resp);
    }

    /**
     * 解除冻结
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void deleteIsFreezed(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int isFreezedUserId = WebUtils.parseInt(req.getParameter("isFreezedUserId"), 0);
        userService.deleteIsFreezed(isFreezedUserId);


        resp.sendRedirect(req.getContextPath() + "/userServlet?action=queryIsFreezedUser");

    }

    /**
     * 冻结用户
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void setIsFreezed(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String currentUserName = req.getParameter("currentUserName");

        Integer currentUserId = blogService.queryUserIdByUserName(currentUserName);


        userService.setIsFreezed(currentUserId);


        resp.sendRedirect(req.getContextPath()+"/blogServlet?action=page&username="+currentUserName);

    }


    /**
     * 修改用户个人信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void updateUserNameAndPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("username");

        String originalUserName = req.getParameter("originalUserName");
        String passWord = req.getParameter("password");
        userService.updateUserNameAndPassword(userName,originalUserName,passWord);
        //让用户重新登录
        logout(req,resp);
//        resp.sendRedirect(req.getContextPath()+"/blogServlet?action=page&username="+userName);

        //        userService.updateUserNameAndPassword();

    }
}